package m;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Hashtable;
 
public class WindowsTaskManager {
 
	/**
	 * 杀死一个进程
	 * @param task 进程号
	 *            
	 */
	public static void killTask(Integer pid) {
		try {
			// 取得任务列表
			Hashtable<Integer, WindowsTask> tasks = getTaskList();
			WindowsTask task = tasks.get(pid);
			if(task != null){
				Runtime.getRuntime().exec("tskill " + pid);
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
	/**
	 * 杀死指定名称的所有进程
	 * @param taskName
	 */
	public static void killTask(String taskName){
		try{
			Hashtable<Integer, WindowsTask> tasks = getTaskList();
			Collection<WindowsTask> allTasks = tasks.values();
			for(WindowsTask task: allTasks){
				if(task.getName().equals(taskName)){
					killTask(task.getPid());
				}
			}
 
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
 
	public static boolean isTaskExist(String taskName){
		try{
			Hashtable<Integer, WindowsTask> tasks = getTaskList();
			Collection<WindowsTask> allTasks = tasks.values();
			for(WindowsTask task: allTasks){
				if(task.getName().equals(taskName)){
					return true;
				}
			}
 
		}catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
 
	/**
	 * 返回当前机器的所有进程
	 * 
	 * @return
	 */
	public static Hashtable<Integer, WindowsTask> getTaskList() {
		Hashtable<Integer, WindowsTask> tasks = new Hashtable<Integer, WindowsTask>();
		try {
			Process process = Runtime.getRuntime().exec("taskList /FO CSV");
			InputStreamReader in = new InputStreamReader(process
					.getInputStream(), "GBK");
			BufferedReader reader = new BufferedReader(in);
			String taskInfo = null;
			WindowsTask task = null;
			String split[] = null;
			String tmp = null;
			while ((taskInfo = reader.readLine()) != null) {
				if (taskInfo.trim().length() > 0
						&& (taskInfo.contains("Services") || taskInfo.contains("Console"))) {
 
					task = new WindowsTask();
					split = taskInfo.split("\",\"");
					tmp = split[0];
					task.setName(tmp.substring(1));
					tmp = split[1];
					task.setPid(Integer.valueOf(tmp));
 
					tmp = split[2];
					task.setSessionName(tmp);
 
					tmp = split[3];
					task.setSessionId(Integer.valueOf(tmp));
 
					tmp = split[4];
					tmp = tmp.replaceAll(",|\"| |K", "");
					task.setMem(Long.valueOf(tmp));
 
					tasks.put(task.getPid(), task);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tasks;
	}
 
	/**
	 * 启动一个进程,传入的值可以是服务名,也可以是可执行文件的全路径名
	 * 
	 * @param task
	 */
	public static void startTask(String task) {
		try {
			Runtime.getRuntime().exec(task);
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 
}